const { no, ok, getClientIp } = require('../../utils/utlis');
const userService = require('../../services/client/userService');
const JWT = require('../../utils/jwt');

module.exports = {
	register: async (req, res, next) => {
		try {
			let { email, username, password, code, captchaKey } = req.body;
			await userService.register(email, username, password, code, captchaKey);
			res.send(ok());
		} catch (error) {
			res.send(no(error.message));
		}
	},
	login: async (req, res, next) => {
		try {
			let { email, password, code, captchaKey } = req.body;
			let ipv6 = getClientIp(req);

			let obj = await userService.login(email, password, code, captchaKey, ipv6);
			res.header('token', obj.token);
			res.send(ok(obj.info));
		} catch (error) {
			res.send(no(error.message));
		}
	},
	forget: async (req, res, next) => {
		try {
			let { email, password, code, captchaKey } = req.body;
			await userService.forget(email, password, code, captchaKey);
			res.send(ok());
		} catch (error) {
			res.send(no(error.message));
		}
	},
	userInfo: async (req, res, next) => {
		try {
			let token = JWT.decrypt(req.headers.token);
			if (!token) return res.send({ code: 66, msg: '未登录/token过期，请登录！' });

			let obj = await userService.userInfo(token.id);
			res.send(ok(obj));
		} catch (error) {
			res.send(no(error.message));
		}
	},
	update: async (req, res, next) => {
		try {
			let { avatar, filename, username, password, gender, website, weixin, mobile, id } = req.body;
			await userService.update(avatar, filename, username, password, gender, website, weixin, mobile, id);
			res.send(ok());
		} catch (error) {
			res.send(no(error.message));
		}
	},
	del: async (req, res, next) => {
		try {
			let { id } = JWT.decrypt(req.headers.token);
			await userService.del(id);
			res.send(ok());
		} catch (error) {
			res.send(no(error.message));
		}
	},
	getBloger: async (req, res, next) => {
		try {
			let obj = await userService.getBloger();
			res.send(ok(obj));
		} catch (error) {
			res.send(no(error.message));
		}
	}
};
